const acorn = require('acorn');
const jsx = require('acorn-jsx');
const https = require('https');
const fs = require('fs');
const path = require('path');
// 配置支持JSX和最新语法
const parser = acorn.Parser.extend(jsx());
// 特性检测规则映射表
const FEATURE_DETECTORS = {
    // 1. let/const
    'let/const': node => 
      node.type === 'VariableDeclaration' && 
      ['let', 'const'].includes(node.kind),
    // 2. 解构赋值 (对象和数组)
    '解构赋值': node => 
      (node.type === 'VariableDeclarator' && 
       (node.id.type === 'ObjectPattern' || node.id.type === 'ArrayPattern')) ||
      (node.type === 'AssignmentPattern' && 
       (node.left.type === 'ObjectPattern' || node.left.type === 'ArrayPattern')),
    // 3. 参数处理
    '默认参数': node => 
      node.type === 'AssignmentPattern' && 
      node.parent.type === 'FunctionParameter',
    '剩余参数': node => 
      node.type === 'RestElement' && 
      node.parent.type === 'FunctionParameter',
    // 4. 生成器函数
    '生成器': node =>
      (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') && 
      node.generator === true,
    // 5. raw标签函数
    'raw标签函数': node =>
      node.type === 'TaggedTemplateExpression' &&
      node.tag.type === 'MemberExpression' &&
      node.tag.object?.name === 'String' &&
      node.tag.property?.name === 'raw',
    // 6. 对象特性
    '对象简写': node => 
      node.type === 'Property' && 
      node.shorthand === true,
    '计算属性名': node =>
      node.type === 'Property' && 
      node.computed === true,
    // 7. 合并语法
    '合并语法': node =>
      node.type === 'SpreadElement' &&
      (node.parent.type === 'ArrayExpression' || node.parent.type === 'ObjectExpression'),
    // 8. 类与继承
    '类定义': node =>
      node.type === 'ClassDeclaration' || 
      node.type === 'ClassExpression',
    '类继承': node =>
      (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') &&
      node.superClass !== null,
    // 9. 模块系统
    '动态导入': node => node.type === 'ImportExpression',
    '模块导入': node => node.type === 'ImportDeclaration',
    '默认导出': node => node.type === 'ExportDefaultDeclaration',
    '命名导出': node => node.type === 'ExportNamedDeclaration',
    //10.eval与with
    'eval调用': node => node.type === 'CallExpression' && node.callee.type === 'Identifier' &&
    node.callee.name === 'eval',
    'with语句': node => node.type === 'WithStatement'
  };


  const zlib = require('zlib');

  // 增强版抓取函数
  async function fetchJS(url) {
    return new Promise((resolve, reject) => {
      https.get(url, (res) => {
        if (res.statusCode !== 200) {
          fs.promises.appendFile(ERROR_LOG, `${url}\n`).catch(() => {});  // 记录错误URL
          return reject(new Error(`HTTP ${res.statusCode}`));
        }
  
        let data = '';
  
        // 检查 Content-Encoding 是否为 gzip
        if (res.headers['content-encoding'] === 'gzip') {
          res.pipe(zlib.createGunzip()).on('data', (chunk) => {
            data += chunk;
          }).on('end', () => {
            console.log(`Fetched and decompressed data with length: ${data.length} characters`);
            resolve(data);
          }).on('error', reject);
        } else {
          res.on('data', (chunk) => {
            data += chunk;
          });
          res.on('end', () => {
            console.log(`Fetched data with length: ${data.length} characters`);
            resolve(data);
          });
        }
      }).on('error', async (err) => {
        await fs.promises.appendFile(ERROR_LOG, `${url}\n`).catch(() => {});  // 记录网络错误
        reject(err);
      });
    });
  }
  
  
// AST遍历检测器
function detectFeatures(ast) {
  const detected = new Set();
  function traverse(node) {
    // 避免空节点
    if (node == null) {
        return;
    }
    // 检查所有检测规则
    for (const [feature, detector] of Object.entries(FEATURE_DETECTORS)) {
      if (detector(node)) detected.add(feature);
    }
    // 递归遍历子节点
    for (const key in node) {
      const child = node[key];
      if (child && typeof child === 'object') {
        if (Array.isArray(child)) {
          child.forEach(traverse);
        } else if (child.type) {
          traverse(child);
        }
      }
    }
  }
  traverse(ast);
  return detected;
}
// 特性检测入口
async function analyzeES6(url) {
  try {
    const code = await fetchJS(url);
    const ast = parser.parse(code, { 
      ecmaVersion: 'latest', 
      sourceType: 'module' 
    });
    
    const features = detectFeatures(ast);
    
    console.log('检测到的ES6+特性:');
    Array.from(features)
      .sort()
      .forEach(f => console.log('►' + f));
  } catch (error) {
    console.error('分析失败:', error);
  }
}
// 使用示例
const TEST_URL = 'https://w3.huawei.com/ihelp/usp/usp/common/js/uspCollect.js?fn=1&appid=M001789&sourceUrl=https%3A%2F%2Flogin-beta.huawei.com%2Flogin1%2F%3Fredirect%3Dhttps%253A%252F%252Ffincloud-uat.finance.huawei.com%252Fsaasone%252F%2523%252Fhome%253FactiveDashboard%253Dea2a4ab0-eb15-429c-a867-f5add9ffc67d%26x_app_id%3Dcom.huawei.jalor.commoncs';
analyzeES6(TEST_URL);

